package com.lishiots.cloud.datacenter.middleware.web;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lishiots.cloud.datacenter.middleware.common.BuildResult;
import com.lishiots.cloud.datacenter.middleware.common.Pagination;
import com.lishiots.cloud.datacenter.middleware.common.RequestPage;
import com.lishiots.cloud.datacenter.middleware.common.RestfulMessage;
import com.lishiots.cloud.datacenter.middleware.entity.Document;
import com.lishiots.cloud.datacenter.middleware.entity.Label;
import com.lishiots.cloud.datacenter.middleware.req.DocumentAddRequest;
import com.lishiots.cloud.datacenter.middleware.req.DocumentQueryRequest;
import com.lishiots.cloud.datacenter.middleware.req.DocumentUpdateRequest;
import com.lishiots.cloud.datacenter.middleware.resp.DocumentResponse;
import com.lishiots.cloud.datacenter.middleware.service.DocumentService;
import com.lishiots.cloud.datacenter.middleware.service.LabelService;
import com.lishiots.cloud.datacenter.middleware.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Chaofan at 2018-11-19 14:04
 * email:chaofan2685@qq.com
 **/
@Api(value = "文档管理",tags = "文档管理")
@RestController
@RequestMapping("/api/doc")
public class DocumentController extends BuildResult {

    @Autowired
    DocumentService documentService;

    @Autowired
    UserService userService;

    @Autowired
    LabelService labelService;

    @Transactional(rollbackFor={RuntimeException.class, Exception.class},propagation= Propagation.REQUIRES_NEW,isolation= Isolation.DEFAULT)
    @ApiOperation(value = "新增文档")
    @PostMapping("/add")
    public RestfulMessage<Boolean> add(DocumentAddRequest requestDoc, HttpServletRequest request){
        Assert.notBlank(requestDoc.getTitle(),"标题不能为空");
        Assert.notBlank(requestDoc.getContent(),"内容不能为空");
        Assert.notBlank(requestDoc.getGitlabUrl(),"下载地址不能为空");
        Assert.notBlank(requestDoc.getLabel(),"标签不能为空");
        Document doc = new Document();
        BeanUtils.copyProperties(requestDoc,doc);
        doc.setUserId(request.getSession().getAttribute("USERID").toString());
        documentService.save(doc);
        List<String> list = Arrays.asList(requestDoc.getLabel().split(","));
        List<Label> labels = new ArrayList<>();
        for (String labelName : list){
            labels.add(new Label(labelName,doc.getId()));
        }
        return mergeObject(labelService.saveBatch(labels));
    }

    @ApiOperation(value = "修改文档")
    @PostMapping("/update")
    public RestfulMessage<Boolean> update(DocumentUpdateRequest requestDoc, HttpServletRequest request){
        Assert.notBlank(requestDoc.getId(),"ID不能为空");
        Assert.notBlank(requestDoc.getTitle(),"标题不能为空");
        Assert.notBlank(requestDoc.getContent(),"内容不能为空");
        Assert.notBlank(requestDoc.getGitlabUrl(),"下载地址不能为空");
        Document doc = new Document();
        BeanUtils.copyProperties(requestDoc,doc);
        String userId = (String) request.getSession().getAttribute("USERID");
        String userId2 = documentService.getById(requestDoc.getId()).getUserId();
        Assert.isTrue(userId2.equals(userId),"您无权修改他人文章");
        documentService.updateById(doc);
        QueryWrapper<Label> wrapper = new QueryWrapper<>();
        wrapper.eq("document_id",doc.getId());
        labelService.remove(wrapper);
        List<String> list = Arrays.asList(requestDoc.getLabel().split(","));
        List<Label> labels = new ArrayList<>();
        for (String labelName : list){
            labels.add(new Label(labelName,doc.getId()));
        }
        return mergeObject(labelService.saveBatch(labels));
    }

    @Transactional(rollbackFor={RuntimeException.class, Exception.class},propagation= Propagation.REQUIRES_NEW,isolation= Isolation.DEFAULT)
    @ApiOperation(value = "删除文档")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "id", name = "id"),
    })
    @GetMapping("/delete")
    public RestfulMessage<Boolean> delete(String id, HttpServletRequest request){
        Assert.notBlank(id,"id不能为空");
        String userId = (String) request.getSession().getAttribute("USERID");
        String userId2 = documentService.getById(id).getUserId();
        Assert.isTrue(userId2.equals(userId),"您无权删除他人文章");
        documentService.removeById(id);
        QueryWrapper<Label> wrapper = new QueryWrapper<>();
        wrapper.eq("document_id",id);
        return mergeObject(labelService.remove(wrapper));
    }

    @ApiOperation(value = "获取文档")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "id", name = "id"),
    })
    @GetMapping("/queryById")
    public RestfulMessage<DocumentResponse> queryById(String id){
        Assert.notBlank(id,"用户id不能为空");
        DocumentResponse response = new DocumentResponse();
        Document document = documentService.getById(id);
        BeanUtils.copyProperties(document,response);
        response.setUserName(userService.getById(document.getUserId()).getName());
        QueryWrapper<Label> wrapper = new QueryWrapper<>();
        wrapper.eq("document_id",response.getId());
        List<String> lableNames = new ArrayList<>();
        labelService.list(wrapper).stream().forEach(label -> lableNames.add(label.getLabelName()));
        response.setLabels(lableNames);
        return mergeObject(response);
    }

    @ApiOperation(value = "分页查询")
    @GetMapping("/queryPage")
    public Pagination<DocumentResponse> queryPage(DocumentQueryRequest requestPage){
        PageHelper.startPage(requestPage.getCurrentPage(), requestPage.getPageSize());
        List<DocumentResponse> list = documentService.queryPage(requestPage);
        for (DocumentResponse doc : list){
            List<String> lableNames = new ArrayList<>();
            QueryWrapper<Label> wrapper = new QueryWrapper<>();
            wrapper.eq("document_id",doc.getId());
            labelService.list(wrapper).stream().forEach(label -> lableNames.add(label.getLabelName()));
            doc.setLabels(lableNames);
        }
        PageInfo pageInfo = new PageInfo(list);
        return handlePagination(pageInfo);
    }

    @ApiOperation(value = "个人中心分页查询")
    @GetMapping("/queryPageByUser")
    public Pagination<Document> queryPageByUser(RequestPage requestPage, HttpServletRequest request){
        String userId = (String) request.getSession().getAttribute("USERID");
        Assert.notBlank(userId,"用户未登录");
        PageHelper.startPage(requestPage.getCurrentPage(), requestPage.getPageSize());
        QueryWrapper<Document> wrapper = new QueryWrapper<>();
        wrapper.select("id","title","create_time");
        wrapper.eq("user_id",userId);
        List<Document> list = documentService.list(wrapper);
        PageInfo pageInfo = new PageInfo(list);
        return handlePagination(pageInfo);
    }



}
